﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
using PIBV;

namespace MTViewer
{
    /// <summary>
    /// Interaction logic for DrawingList.xaml
    /// </summary>
    public partial class DrawingList2 : UserControl
    {
        public event EventHandler<LoadDrawingEventArgs> OnDropDrawing;
        PID_DrawingList dataObj;

        public bool IsDown;
        public bool IsDragging;
        private UIElement DragSource;
        private Point StartPoint;
        private object DragContent;

        Image dragDropImage;
        
        public void InitializeControl(Image img)
        {
            dragDropImage = img;
            dataObj = App.DbManager.DrawingListInstance;
            dataObj.InitializeData(true, true);
        }

        public DrawingList2()
        {
            InitializeComponent();
            //dataObj = App.DbManager.DrawingListInstance;
            //dataObj.InitializeData(true, true);
        }

        void FillListBox()
        {
            if (dataObj != null)
            {
                lstDrawings.ItemsSource = dataObj.GetDrawingsByLoopName(txtFilter.Text);
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FillListBox();
        }

        private void txtFilter_TextChanged(object sender, TextChangedEventArgs e)
        {
            FillListBox();
        }

        #region DragDrop

        private void EndDrag()
        {
            Forget();
        }

        private void CancelDrag()
        {
            Forget();
        }

        private void Forget()
        {
            Debug.WriteLine("Forget");
            if (this.IsMouseCaptured) this.ReleaseMouseCapture();
            IsDragging = false;
            IsDown = false;
            DragContent = null;
            DragSource = null;
        }

        #endregion

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Debug.WriteLine("Enter Grid_MouseDown");

            DragContent = lstDrawings.SelectedItem;

            if (DragContent != null)
            {
                IsDown = true;
                StartPoint = e.GetPosition(this);
                DragSource = e.Source as UIElement;
            }
        }

        private void Grid_MouseMove(object sender, MouseEventArgs e)
        {
            if (IsDown)
            {
                Debug.WriteLine("Enter Grid_MouseMove");
                Point Position = e.GetPosition(this);

                if (!IsDragging && (Math.Abs(Position.X - StartPoint.X) > 2 * SystemParameters.MinimumHorizontalDragDistance))
                {
                    StartDrag();
                }

                {
                    Point pos = e.GetPosition(this);
                    dragDropImage.SetValue(Canvas.TopProperty, pos.Y);
                    dragDropImage.SetValue(Canvas.LeftProperty, pos.X);
                };
            }
            
            // В процессе драга поглощаем события о движении мышы. В этом случае элементы находящиеся выше в визуальном дереве не смогут инициировать свой драг.
            if (IsDragging)
            {
                e.Handled = true;
            }
        }

        private void Grid_MouseUp(object sender, MouseButtonEventArgs e)
        {
            IsDragging = false;
            IsDown = false;
            CancelDrag();
        }

        private void StartDrag()
        {
            IsDragging = true;

            this.CaptureMouse();

            long loopId = Convert.ToInt64(lstDrawings.SelectedValue);
            LoadDrawingEventArgs res = dataObj.GetFileName(loopId, Properties.Settings.Default.TiffStoragePath);
            DragDrop.DoDragDrop((UIElement)lstDrawings, res , DragDropEffects.Copy);

            EndDrag();
        }

        object _selectedItem = null;
        bool _IsTouchMoving = false;

        private void lstDrawings_TouchDown(object sender, TouchEventArgs e)
        {
            Debug.WriteLine("TouchDown");

            _IsTouchMoving = false;
            TouchPoint pos = e.GetTouchPoint(this);

            if (pos.Action == TouchAction.Down)
            {
                _selectedItem = lstDrawings.SelectedItem;
                StartPoint = this.PointToScreen(e.GetTouchPoint(this).Position);
            }
        }

        private void lstDrawings_TouchEnter(object sender, TouchEventArgs e)
        {
            Debug.WriteLine("TouchEnter");
        }

        private void lstDrawings_TouchLeave(object sender, TouchEventArgs e)
        {
            Debug.WriteLine("TouchLeave");
        }

        private void lstDrawings_TouchMove(object sender, TouchEventArgs e)
        {
            Debug.WriteLine("TouchMove");

            TouchPoint pos = e.GetTouchPoint(this);
            Point Position = this.PointToScreen(pos.Position);

            if ((pos.Action == TouchAction.Move)
                && (Math.Abs(StartPoint.X - Position.X) > 2 * SystemParameters.MinimumHorizontalDragDistance)
                && (_selectedItem == lstDrawings.SelectedItem))
            {
                dragDropImage.SetValue(Canvas.TopProperty, Position.Y);
                dragDropImage.SetValue(Canvas.LeftProperty, Position.X);
                dragDropImage.Visibility = System.Windows.Visibility.Visible;
                _IsTouchMoving = true;
            }
            else
            {
                dragDropImage.Visibility = System.Windows.Visibility.Hidden;
                _IsTouchMoving = false;
            }
        }

        private void lstDrawings_TouchUp(object sender, TouchEventArgs e)
        {
            Debug.WriteLine("TouchUp");
            TouchPoint pos = e.GetTouchPoint(this);
            Point Position = this.PointToScreen(pos.Position);

            if ((pos.Action == TouchAction.Up) && _IsTouchMoving)
            {
                dragDropImage.Visibility = System.Windows.Visibility.Hidden;

                if (OnDropDrawing != null)
                {
                    long loopId = Convert.ToInt64(lstDrawings.SelectedValue);
                    LoadDrawingEventArgs args = dataObj.GetFileName(loopId, Properties.Settings.Default.TiffStoragePath);
                    if (args != null)
                    {
                        args.Position = Position;
                        OnDropDrawing(this, args);
                    }
                }
            }
            _IsTouchMoving = false;
        }

    }
}

